﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Runtime.InteropServices;
using ServiceStack.Redis;
using ServiceStack.Redis.Generic;
using System.Web;
using System.Web.UI;
using System.Xml;
using ServiceStack.Text;

namespace Redis
{

    public class RedisHelper : IDisposable
    {

        static string RedeisServer = "";
        static string RedisServerProt = "";
        static string RedisUrl = "";
        public RedisClient Redis = new RedisClient(RedeisServer, int.Parse(RedisServerProt));

        static RedisHelper()
        {
            if (RedisUrl == "" || RedeisServer == "" || RedisServerProt == "")
            {
                RedisUrl = RedeisServerUrl();
            }
        }

        public static string RedeisServerUrl()
        {

            string XmlPath = HttpContext.Current.Server.MapPath("~/System.config");
            XmlDocument xml = new XmlDocument();
            xml.Load(XmlPath);
            RedeisServer = xml.DocumentElement.GetElementsByTagName("RedisServer")[0].InnerXml;
            RedisServerProt = xml.DocumentElement.GetElementsByTagName("RedisServerProt")[0].InnerXml;
            return RedeisServer + ":" + RedisServerProt;

        }
        //缓存池
        PooledRedisClientManager prcm = new PooledRedisClientManager();

        //默认缓存过期时间单位秒
        public int secondsTimeOut = 30 * 60;

        /// <summary>
        /// 缓冲池
        /// </summary>
        /// <param name="readWriteHosts"></param>
        /// <param name="readOnlyHosts"></param> nmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
        /// <returns></returns>
        public static PooledRedisClientManager CreateManager(string[] readWriteHosts, string[] readOnlyHosts)
        {
            return new PooledRedisClientManager(readWriteHosts, readOnlyHosts,
                new RedisClientManagerConfig
                {
                    MaxWritePoolSize = readWriteHosts.Length * 5,
                    MaxReadPoolSize = readOnlyHosts.Length * 5,
                    AutoStart = true,
                });
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="OpenPooledRedis">是否开启缓冲池</param>
        public RedisHelper(bool OpenPooledRedis = false)
        {

            if (OpenPooledRedis)
            {
                prcm = CreateManager(new string[] { RedisUrl }, new string[] { RedisUrl });
                Redis = prcm.GetClient() as RedisClient;
            }
        }

        #region Key/Value存储

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">缓存建</param>
        /// <param name="t">缓存值</param>
        /// <param name="timeout">过期时间，单位秒,-1：不过期，0：默认过期时间</param>
        /// <returns></returns>
        public bool Set<T>(string key, T t, int timeout = 0)
        {
            if (timeout >= 0)
            {
                if (timeout > 0)
                {
                    secondsTimeOut = timeout;
                }
                DateTime dtTimeOut = DateTime.Now.AddSeconds(secondsTimeOut);
                return Redis.Set<T>(key, t, dtTimeOut);
            }

            return Redis.Set<T>(key, t);
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T Get<T>(string key)
        {
            return Redis.Get<T>(key);
        }

        ///// <summary>
        ///// 从redis中获取缓存，如果没有，则添加
        ///// </summary>
        ///// <typeparam name="T"></typeparam>
        ///// <param name="key">缓存键名</param>
        ///// <param name="acquirer">要缓存的结果</param>
        ///// <param name="cacheTime">从当前时间起的缓存秒数，默认为15天，15*24*60*60=1296000， 24小时对应的秒数为86400</param>
        ///// <returns></returns>
        //public T Get<T>(string key, Func<T> acquirer, int cacheTime = 1296000)
        //{
        //    if (Redis.Exists(key) == 1) // 键存在
        //    {
        //        return Redis.Get<T>(key);
        //    }

        //    // 键不存在
        //    var value = acquirer();
        //    Redis.Set(key, value, DateTime.Now.AddSeconds(cacheTime));
        //    return value;
        //}

        ///// <summary>
        ///// 根据key的pattern模糊搜索<br />
        ///// 参考文档：http://www.cnblogs.com/capqueen/p/HowToUseRedis.html#!comments
        ///// </summary> 
        ///// <param name="pattern"></param>
        ///// <returns></returns>
        //public Dictionary<string, T> MGet<T>(string pattern)
        //{
        //    List<string> keys = Redis.SearchKeys(pattern);
        //    return Redis.GetValuesMap<T>(keys);
        //}

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool Remove(string key)
        {
            using (var client = this.Redis)
            {
                return client.Remove(key);
            }
        }

        /// <summary>
        /// 增加
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="t"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public bool Add<T>(string key, T t, int timeout)
        {
            if (timeout >= 0)
            {
                if (timeout > 0)
                {
                    secondsTimeOut = timeout;
                }
                Redis.Expire(key, secondsTimeOut);
            }
            return Redis.Add<T>(key, t);
        }

        #endregion

        #region 链表操作

        /// <summary>
        /// 根据IEnumerable数据添加链表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="listId"></param>
        /// <param name="values"></param>
        /// <param name="timeout"></param>
        public void AddList<T>(string listId, IEnumerable<T> values, int timeout = 0)
        {
            IRedisTypedClient<T> iredisClient = Redis.As<T>();
            var redisList = iredisClient.Lists[listId];
            redisList.AddRange(values);
            if (timeout >= 0)
            {
                if (timeout > 0)
                {
                    secondsTimeOut = timeout;
                }
                Redis.Expire(listId, secondsTimeOut);
            }
        }

        /// <summary>
        /// 添加单个实体到链表中
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="listId"></param>
        /// <param name="Item"></param>
        /// <param name="timeout"></param>
        public void AddEntityToList<T>(string listId, T Item, int timeout = 0)
        {
            IRedisTypedClient<T> iredisClient = Redis.As<T>();

            var redisList = iredisClient.Lists[listId];
            redisList.Add(Item);
            iredisClient.Save();
            if (timeout >= 0)
            {
                if (timeout > 0)
                {
                    secondsTimeOut = timeout;
                }
                Redis.Expire(listId, secondsTimeOut);
            }

        }

        /// <summary>
        /// 获取链表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="listId"></param>
        /// <returns></returns>
        public IEnumerable<T> GetList<T>(string listId)
        {
            IRedisTypedClient<T> iredisClient = Redis.As<T>();
            return iredisClient.Lists[listId];
        }

        /// <summary>
        /// 在链表中删除单个实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="listId"></param>
        /// <param name="t"></param>
        public void RemoveEntityFromList<T>(string listId, T t)
        {
            IRedisTypedClient<T> iredisClient = Redis.As<T>();
            var redisList = iredisClient.Lists[listId];
            redisList.RemoveValue(t);
            iredisClient.Save();
        }

        /// <summary>
        /// 根据lambada表达式删除符合条件的实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="listId"></param>
        /// <param name="func"></param>
        public void RemoveEntityFromList<T>(string listId, Func<T, bool> func)
        {
            IRedisTypedClient<T> iredisClient = Redis.As<T>();
           
                var redisList = iredisClient.Lists[listId];
                T value = redisList.Where(func).FirstOrDefault();
                redisList.RemoveValue(value);
                iredisClient.Save();
            
        }

        #endregion

        //距离过期时间还有多少秒
        public long TTL(string key)
        {
            return Redis.Ttl(key);
        }

        public void Expire(string key, int Seconds)
        {
            Redis.Expire(key, Seconds);
        }

        //释放资源
        public void Dispose()
        {
            if (Redis != null)
            {
                Redis.Dispose();
                Redis = null;
            }
            GC.Collect();

        }

        #region redis hash 相关操作

        public IDictionary<TKey, TValue> GetHash<TKey, TValue>(string hashId, Func<IDictionary<TKey, TValue>> acquirer)
        {
            using (var client = this.Redis)
            {
                var redis = client.As<TValue>();
                if (!redis.ContainsKey(hashId))
                {
                    var hash = redis.GetHash<TKey>(hashId); 
                    var result = acquirer(); 
                    foreach (var item in result)
                    {
                        redis.SetEntryInHash(hash, item.Key, item.Value); 
                    }

                    return result;
                }
                else
                {
                    var hash = redis.GetHash<TKey>(hashId);
                    return hash;
                }
            }
        }

        #endregion

        public bool SetEntryInHash<TKey, TValue>(string hashId, TKey key, TValue value)
        {
            using (var client = this.Redis)
            {
                var redis = client.As<TValue>();
                var hash = redis.GetHash<TKey>(hashId);
                return redis.SetEntryInHash(hash, key, value);
            }
        }

        public TValue GetValueFromHash<TKey, TValue>(string hashId, TKey key)
        {
            using (var client = this.Redis)
            {
                var redis = client.As<TValue>();
                var hash = redis.GetHash<TKey>(hashId);
                return redis.GetValueFromHash(hash, key);
            }
        }

        /// <summary>
        /// 从指定hashId中删除指定键值
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="hashId"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool RemoveEntryFromHash<TKey, TValue>(string hashId, TKey key)
        {
            using (var client = this.Redis)
            {
                var redis = client.As<TValue>();
                return redis.RemoveEntryFromHash(redis.GetHash<TKey>(hashId), key);
            }
        }

        /// <summary>
        /// 用于判断redis中指定的key是否存在
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool ContainsKey(string key)
        {
            using (var client = this.Redis)
            {
                return client.ContainsKey(key);
            }
        }
    }
   
}
